﻿using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

using LuaNET.LuaJIT;
using static LuaNET.LuaJIT.Lua;
using System.Collections.ObjectModel;
using System.Windows.Input;

namespace ToolPlus.ViewModel
{
    public partial class MainViewModel : ViewModelBase
    {
        #region Properties
        private string _title;
        private bool _customScirptPath;
        public string AppTitle { get => _title; set => SetProperty(ref _title, value); }
        public bool IsCustomScriptPath { get => _customScirptPath; set => SetProperty(ref _customScirptPath, value); }

        ObservableCollection<ButtonViewModel> _buttons;
        public ObservableCollection<ButtonViewModel> Buttons { get => _buttons; set => SetProperty(ref _buttons, value); }

        private Window window;
        #endregion
        #region ctor

        public MainViewModel(Window window)
        {
            this.window = window;

            init();

            initApp();
        }
        #endregion

        #region Methods
        private void init()
        {
            Log.Verbose("init application");
            Buttons = new ObservableCollection<ButtonViewModel>
            {
                new ButtonViewModel { ButtonText = "Button 1" },
                new ButtonViewModel { ButtonText = "Button 2" },
                new ButtonViewModel { ButtonText = "Button 3" },
                // Add more buttons as needed
            };
        }
        static int printx(lua_State L)
        {
            string output = "";  // 用于存储输出的字符串

            int n = lua_gettop(L);  // 获取栈上参数的数量

            for (int i = 1; i <= n; i++)
            {
                var str = lua_tostring(L, i);  // 获取参数的字符串表示
                if (!string.IsNullOrEmpty(str))
                {
                    output += str;
                }
                else
                {
                    output += "[non-string]";
                }

                if (i < n)
                {
                    output += " ";
                }
            }


            // 将输出追加到编辑框
            //if (g_pDialog)
            //{
            //    g_pDialog->setEditMessage(output);
            //}
            Log.Debug(output);

            return 0;  // 返回值表示压入栈的结果数量
        }
        private void runScript(string scriptPath)
        {
            Log.Debug($"========================== test script {scriptPath} =============================");

            lua_State L = luaL_newstate();
            if (L.Handle == 0)
            {
                Trace.WriteLine("Unable to create context!");
            }
            luaL_openlibs(L);

            // 注册自定义函数
            lua_pushcfunction(L, printx);
            lua_setglobal(L, "printx");

            // 打开文件
            if (LUA_OK != luaL_loadfile(L, scriptPath) || LUA_OK != lua_pcall(L, 0, 0, 0))
            {
                // 处理加载和运行错误
                string? err = lua_tostring(L, -1) ?? "未知错误";

                MessageBox.Show(err);
            }

            Trace.WriteLine(lua_pcall(L, 0, 0, 0));
            lua_close(L);

            Trace.WriteLine("Success");
        }

        static string OpenFile()
        {
            // 创建 OpenFileDialog 实例
            OpenFileDialog openFileDialog = new OpenFileDialog();

            // 设置对话框的标题
            openFileDialog.Title = "选择文件";

            // 设置对话框的过滤器，以限制用户选择的文件类型
            openFileDialog.Filter = "脚本文件 (*.lua)|*.lua|所有文件 (*.*)|*.*";

            // 显示对话框并检查用户是否点击了“确定”按钮
            bool? result = openFileDialog.ShowDialog();

            // 如果用户点击了“确定”，返回所选文件的路径
            if (result == true)
            {
                return openFileDialog.FileName;
            }
            else
            {
                return null;
            }
        }

        #region Clicked

        private void reloadClicked(object obj)
        {
            throw new NotImplementedException();
        }

        private void testScriptClicked(object obj)
        {
            if (IsCustomScriptPath)
            {
                // 调用函数以获取用户选择的文件路径
                string? selectedFilePath = OpenFile();

                // 如果用户选择了文件，打印文件路径
                if (selectedFilePath != null)
                {
                    Trace.WriteLine($"Selected File: {selectedFilePath}");
                    runScript(selectedFilePath);
                }
                else
                {
                    Trace.WriteLine("No file selected.");
                }
            }
            else
            {
                runScript("test.lua");
            }
        }

        private void buttonClicked(object obj)
        {
            var btn = obj as ButtonViewModel;
            Trace.WriteLine(btn.ButtonText);
        }
        #endregion

        #endregion
        #region Commands
        private RelayCommand _reloadCommand, _testScriptCommand, _buttonClickCommand;
        public RelayCommand ReloadCommand => _reloadCommand ?? (_reloadCommand = new RelayCommand(reloadClicked));
        public RelayCommand TestScriptCommand => _testScriptCommand ?? (_testScriptCommand = new RelayCommand(testScriptClicked));

        public RelayCommand ButtonClickCommand => _buttonClickCommand ?? (_buttonClickCommand = new RelayCommand(buttonClicked));




        #endregion
    }
}
